﻿using System.Collections.Generic;
using System.Diagnostics;
using Game.Common;
using Game.Level;
using Game.Map;
using Game.Map.Extensions;
using Game.Objects;

namespace Game.Controller.Internal
{
    class StartTurnVisitor 
    {
        readonly GameController _Controller;
        
        Vehicle _CurrentVehicle;
        List<Vehicle> _Vehicles;
        int _Index;
        
        public void Reset()
        {
            _Vehicles = null;
            _Index = 0;
            _CurrentVehicle = null;
        }
        
        public StartTurnVisitor(GameController controller)
        {
            _Controller = controller;
        }
        
        public void SetupVehicles(IGameMap map, GameTurn turn)
        {
            var vehicles = new List<Vehicle>();
            foreach(var field in map.Fields)
            {
                var vehicle = field.VehicleX().Vehicle;
                
                if (vehicle == null)
                {
                    continue;
                }
                
                if (turn.PlayerWithTurn != vehicle.Owner)
                {
                    continue;
                }
                
                //if (turn.NumberOfActionsAssigned > 0)
                //{
                //    continue;
                //}
            
                vehicles.Add(vehicle);
            }
            _Vehicles = vehicles;
        }
        
        public void Execute(
            IGameMap map,
            GameLevels levels,
            TurnHandler handler,
            GameTurn gameTurn)
        {
            if (_Vehicles == null)
            {
                SetupVehicles(map, gameTurn);
            }

            Debug.Assert(_Vehicles != null, "_Vehicles != null");
            if (_Vehicles.Count == 0)
            {
                return;
            }
            
            if (_CurrentVehicle == null)
            {
                _Index = 0;
                _CurrentVehicle = _Vehicles[_Index];
            }

            int i;
            for(i = _Index; i < _Vehicles.Count; i++)
            {
                _CurrentVehicle = _Vehicles[i];

                var test = _Controller.GameMap.FindItem(_CurrentVehicle);
                if (test == null)
                {
                    continue;
                }

                handler.OnStartTurn(
                    _CurrentVehicle, _Controller.GameMap, levels,
                    _Controller.CommandExecutor, 
                    _Controller, gameTurn);

                if (!_Controller.CommandExecutor.IsRunning)
                {
                    continue;
                }
                
                break;
            }

            _Index = i;
        }
        
    }
}
